<template>
  <div id="homeView">
    <div class="container">
      <div class="title-section">
        <h1>一句话呈所想</h1>
        <p>与 AI 对话轻松创建应用和网站</p>
      </div>

      <!-- 输入框部分 -->
      <div class="input-section">
        <a-textarea
          class="input-area"
          v-model:value="userPrompt"
          placeholder="帮我创建个人博客网站"
          :row="4"
          :maxLength="1000"
          :auto-size="{ maxRows: 3 }"
          @press-enter="handleSend"
        />
        <div class="input-actions">
          <a-button @click="handleSend" :loading="loading">
            <template #icon>
              <!-- <SendOutlined /> -->
              <span>↑</span>
            </template>
          </a-button>
        </div>
      </div>

      <!-- 快捷按钮 -->
      <div class="quick-actions">
        <a-button type="default" @click="setPrompt('帮我创建一个个人博客网站，不超过十行代码')"
          >个人博客网站</a-button
        >
        <a-button type="default" @click="setPrompt('帮我创建企业网站，不超过十行代码')"
          >企业网站</a-button
        >
        <a-button type="default" @click="setPrompt('帮我创建电商运营后台，不超过十行代码')"
          >电商运营后台</a-button
        >
        <a-button type="default" @click="setPrompt('帮我创建在线商城，不超过十行代码')"
          >在线商城</a-button
        >
      </div>

      <!-- 作品展示部分 -->
      <div class="works-section" v-if="myApp.length">
        <h2>我的作品</h2>
        <div class="app-grid">
          <AppCard
            v-for="app in myApp"
            :key="app.id"
            :app="app"
            @view-chat="handleViewChat"
            @view-work="handleViewWork"
          />
        </div>
        <div class="pagination-wrapper">
          <a-pagination
            v-model:page-size="myAppPage.pageSize"
            v-model:current="myAppPage.current"
            :total="myAppPage.total"
            :show-size-changer="false"
            :show-total="(total: number) => `共 ${total} 个应用`"
            @change="loadMyApps"
          ></a-pagination>
        </div>
      </div>

      <!-- 精选案例 -->
      <div class="works-section" v-if="featuredApps.length">
        <h2>精选作品</h2>
        <div class="app-grid">
          <AppCard
            v-for="app in featuredApps"
            :key="app.id"
            :app="app"
            @view-chat="handleViewChat"
            @view-work="handleViewWork"
          />
        </div>
        <div class="pagination-wrapper">
          <a-pagination
            v-model:page-size="featuredAppPage.pageSize"
            v-model:current="featuredAppPage.current"
            :total="featuredAppPage.total"
            :show-size-changer="false"
            :show-total="(total: number) => `共 ${total} 个应用`"
            @change="loadFeaturedApps"
          ></a-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { handleError, onMounted, reactive, ref, onActivated } from 'vue'
import { SendOutlined } from '@ant-design/icons-vue'
import AppCard from '@/components/AppCard.vue'
import { useLoginUserStore } from '@/stores/loginUser'
import { addApp, listGoodAppVoByPage, listMyAppVoByPage } from '@/api/appController'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { getDeployConfig } from '@/config/deploy'

const userPrompt = ref<String>('')
const loading = ref<Boolean>(false)

const loginUserStore = useLoginUserStore()
const router = useRouter()

// 我的应用数据
const myApp = ref<API.AppVo[]>([])
const myAppPage = reactive({
  current: 1,
  pageSize: 6,
  total: 0,
})

// 精选作评数据
const featuredApps = ref<API.AppVo[]>([])
const featuredAppPage = reactive({
  current: 1,
  pageSize: 6,
  total: 0,
})

// 发送数据
const handleSend = async () => {
  if (!userPrompt.value) {
    message.error('请输入提示词')
    return
  }

  if (!loginUserStore.loginUser.id) {
    message.error('请先登录')
    return
  }
  loading.value = true
  try {
    const res = await addApp({
      initPrompt: userPrompt.value.trim(),
    })

    if (res.data.code === 0 && res.data.data) {
      message.success('创建成功')
      const appId = String(res.data.data)
      console.log(appId, 'aaa')

      router.push(`/app/chat/${appId}`)
    } else {
      message.error('创建失败:', +(res.data.message || '未知错误'))
    }
  } catch (error: any) {
    console.log('创建失败:', +error)
  } finally {
    loading.value = false
  }
}

// 设置提示词
const setPrompt = (promp: string) => {
  userPrompt.value = promp
}

const loadMyApps = async () => {
  if (!loginUserStore.loginUser.id) {
    return
  }
  try {
    const res = await listMyAppVoByPage({
      pageNum: myAppPage.current,
      pageSize: myAppPage.pageSize,
      // userId: loginUserStore.loginUser.id
      sortField: 'createTime',
      sortOrder: 'desc',
    })

    if (res.data.code === 0 && res.data.data) {
      myApp.value = res.data.data.records || []
      myAppPage.total = res.data.data.totalRow || 0
    }
  } catch (error) {
    console.log(error, '获取我的应用失败')
  }
}

const loadFeaturedApps = async () => {
  try {
    const res = await listGoodAppVoByPage({
      pageNum: featuredAppPage.current,
      pageSize: featuredAppPage.pageSize,
      sortField: 'priority',
      sortOrder: 'desc',
    })
    if (res.data.code === 0 && res.data.data) {
      featuredApps.value = res.data.data.records?.filter((item) => item.priority !== 0) || []
      // featuredAppPage.total = res.data.data.totalRow || 0
      featuredAppPage.total = featuredApps.value.length
    }
  } catch (error) {
    console.log(error, '获取推荐应用失败')
  }
}

const handleViewChat = (appId: number | string | undefined) => {
  if (!appId) return
  router.push(`/app/chat/${appId}?view=1`)
  console.log('查看聊天')
}

const handleViewWork = (app: API.AppVo) => {
  if (!app.deployKey) return
  const url = getDeployConfig(app.deployKey)
  // const url = getDeployUrl(app.deployKey)
  window.open(url, '_blank')
}

// 关键：每次进入首页（包括从缓存返回）都执行请求
onActivated(() => {
  loadMyApps()
  loadFeaturedApps()
});

// 若首页可能在未缓存的场景下首次加载，可补充 onMounted（与 onActivated 不冲突
onMounted(() => {
  loadMyApps()
  loadFeaturedApps()
})
</script>

<style scoped>
#homeView {
  width: 100%;
  margin: 0;
  padding: 0;
  min-height: calc(100vh - 135px);
  /* max-height: calc(100vh - 68px); */
  position: relative;
  overflow: hidden;
  background:
    linear-gradient(to top, #d9afd9 0%, #97d9e1 100%),
    /* linear-gradient(180deg, #f8fafc 0%, #f1f5f9 8%, #e2e8f0 20%, #cbd5e1 100%), */
      radial-gradient(circle at 20% 80%, rgba(59, 130, 246, 0.15) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(139, 92, 246, 0.12) 0%, transparent 50%),
    radial-gradient(circle at 40% 40%, rgba(16, 185, 129, 0.08) 0%, transparent 50%);
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  position: relative;
  z-index: 2;
  width: 100%;
  box-sizing: border-box;
}

.title-section {
  text-align: center;
  padding: 80px 0 60px;
  margin-bottom: 28px;
  color: #1e293b;
  position: relative;
  overflow: hidden;
}

.title-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background:
    radial-gradient(ellipse 800px 400px at center, rgba(59, 130, 246, 0.12) 0%, transparent 70%),
    linear-gradient(45deg, transparent 30%, rgba(139, 92, 246, 0.05) 50%, transparent 70%),
    linear-gradient(-45deg, transparent 30%, rgba(16, 185, 129, 0.04) 50%, transparent 70%);
  animation: heroGlow 10s ease-in-out infinite alternate;
}

@keyframes heroGlow {
  0% {
    opacity: 0.6;
    transform: scale(1);
  }
  100% {
    opacity: 1;
    transform: scale(1.02);
  }
}

.title-section h1 {
  font-size: 48px;
  font-weight: 700;
  line-height: 1.2;
  margin: 0;
  color: #1e293b;
}

.title-section p {
  font-size: 20px;
  font-weight: 400;
  line-height: 1.5;
  margin: 20px 0 0;
}

.input-section {
  position: relative;
  margin: 0 auto 40px;
  max-width: 800px;
}

.input-area {
  /* position: relative; */
  border-radius: 16px;
  border: none;
  padding: 20px 60px 20px 20px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
}

.input-area:focus {
  background: rgba(255, 255, 255, 1);
  box-shadow: 0 15px 50px rgba(0, 0, 0, 0.3);
  transform: translateY(-2px);
}

.input-actions {
  position: absolute;
  bottom: 12px;
  right: 12px;
  display: flex;
  gap: 8px;
  align-items: center;
}

.quick-actions {
  position: relative;
  display: flex;
  gap: 10px;
  justify-content: center;
  flex-wrap: wrap;
}

.quick-actions .ant-btn {
  border-radius: 25px;
  height: auto;
  padding: 8px 20px;
  font-size: 14px;
  backdrop-filter: blur(15px);
  color: #475569;
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(59, 130, 246, 0.2);
  transform: all 0.3s;
  position: relative;
  overflow: hidden;
}

.quick-actions .ant-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(59, 130, 246, 0.1), transparent);
  transition: left 0.5s;
}

.quick-actions .ant-btn:hover::before {
  left: 100%;
}

.quick-actions .ant-btn:hover {
  background: rgba(255, 255, 255, 0.9);
  border-color: rgba(59, 130, 246, 0.4);
  transform: translateY(-5px);
  color: #3b82f6;
  box-shadow: 0 8px 24px rgba(59, 130, 246, 0.2);
}

.app-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.pagination-wrapper {
  text-align: center;
}
</style>
